from typing import Any
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response import Response
from rest_framework.views import APIView
from collections import OrderedDict
from backend.schema.page_schema import PaginateQueryParamsSchema, PaginateParamsParamsSchema

class PageLimitOffsetPagination(LimitOffsetPagination):
    max_limit = 50
    def paginate_queryset(self, queryset, request , view: APIView | None = ...) -> list | None:
        query_params = PaginateQueryParamsSchema(limit=request.query_params["page_size"], offset=request.query_params["page_num"])
        request_params = PaginateParamsParamsSchema(query_params=query_params.model_dump())

        self.limit = self.get_limit(request_params)
        if self.limit is None:
            return None

        self.count = self.get_count(queryset)
        self.offset = self.get_offset(request_params)
        self.request = request
        if self.count > self.limit and self.template is not None:
            self.display_page_controls = True

        if self.count == 0 or self.offset > self.count:
            return []
        return list(queryset[self.offset:self.offset + self.limit])
    
    def get_paginated_response(self, data: Any) -> Response:
        return Response(OrderedDict([
            ('count', self.count),
            ('results', data)
        ]))